package com.bezdelnick.forum.web.component;

import com.bezdelnick.forum.domain.AppUser;
import com.bezdelnick.forum.web.page.IndexPage;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.model.CompoundPropertyModel;

/**
 * Created by IntelliJ IDEA.
 * User: Bezdelnick
 * Date: 16.08.12
 * Time: 23:36
 * To change this template use File | Settings | File Templates.
 */
public class LoginForm extends Form {
    private boolean userRequest;

    private AppUser appUserForModel;
    //private String username;
    //private String password;

    public LoginForm(String id) {
        super(id);
    }

    public LoginForm(String id, boolean userRequest) {
        super(id);
        this.userRequest = userRequest;
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        appUserForModel = new AppUser();

        setModel(new CompoundPropertyModel(appUserForModel));
        add(new RequiredTextField("username"));
        add(new PasswordTextField("password"));
    }

    @Override
    protected void onSubmit() {

        AuthenticatedWebSession session = AuthenticatedWebSession.get();
        if (session.signIn(appUserForModel.getUsername(), appUserForModel.getPassword())) {
            if (!this.userRequest) {
                setDefaultResponsePageIfNecessary();
            } else {
                setResponsePage(getApplication().getHomePage());
            }
        } else {
            error("Login failed");
        }
    }

    private void setDefaultResponsePageIfNecessary() {
        if (!continueToOriginalDestination()) {
            setResponsePage(getApplication().getHomePage());
        }
    }
}
